<template>
  <div class="padding-16">
    <a-card class="general-card" title="岗位管理">
      <a-form
        ref="refSearchForm"
        :model="searchForm"
        auto-label-width
      >
        <a-row :gutter="16">
          <a-col :span="8">
            <a-form-item field="name" label="岗位名称">
              <a-input v-model="searchForm.name" placeholder="请输入岗位名称" />
            </a-form-item>
          </a-col>
          <a-col :span="8">
            <a-form-item field="status" label="状态">
              <a-select v-model="searchForm.status" :options="statusOptions" placeholder="全部" />
            </a-form-item>
          </a-col>
          <a-col :span="8">
            <a-space :size="16">
                <a-button type="primary" @click="handleSearch(1)">
                  <template #icon>
                    <icon-search />
                  </template>
                  查询
                </a-button>
                <a-button @click="$refs.refSearchForm.resetFields()">
                  <template #icon>
                    <icon-refresh />
                  </template>
                  重置
                </a-button>
              </a-space>
          </a-col>
        </a-row>
      </a-form>
      <a-divider style="margin-top: 0" />
      <a-space style="margin-bottom: 16px">
        <a-button size="small" type="primary" @click="handleEdit({})">
          <template #icon>
            <icon-plus />
          </template>
          新增
        </a-button>
      </a-space>
      <a-table
        bordered
        row-key="id"
        :data="tableData"
        :loading="pageLoading"
        :pagination="pageData"
        @page-change="handleSearch"
      >
        <template #columns>
          <a-table-column title="岗位名称" data-index="name"></a-table-column>
          <a-table-column title="岗位编码" data-index="code"></a-table-column>
          <a-table-column title="状态" data-index="status">
            <template #cell="{ record }">
              <DictBadge :options="statusOptions" :value="record.status"/>
            </template>
          </a-table-column>
          <a-table-column title="排序" data-index="sort"></a-table-column>
          <a-table-column title="备注" data-index="remark"></a-table-column>
          <a-table-column title="创建时间" data-index="create_time"></a-table-column>
          <a-table-column title="操作" :width="160">
            <template #cell="{ record }">
              <a-button type="text" @click="handleEdit(record)">编辑</a-button>
              <a-popconfirm content="删除后不可恢复，确定要删除吗？" @ok="handleDelete(record)">
                <a-button type="text" status="danger">删除</a-button>
              </a-popconfirm>
            </template>
          </a-table-column>
        </template>
      </a-table>
    </a-card>

    <!-- 新增 & 编辑 弹窗 -->
    <a-modal
      v-model:visible="dialogVisible"
      width="680px"
      :title="`${formState.id ? '编辑' : '创建'}岗位`"
      :footer="false">
      <a-form
        ref="formRef"
        auto-label-width
        :model="formState"
        :rules="formRules"
        @submit="handleSubmit"
      >
        <a-form-item label="岗位名称" field="name">
          <a-input v-model="formState.name" placeholder="请输入岗位名称"></a-input>
        </a-form-item>

        <a-form-item label="岗位编码" field="code">
          <a-input v-model="formState.code" placeholder="请输入岗位编码"></a-input>
        </a-form-item>

        <a-form-item label="排序" field="sort">
          <a-input-number v-model="formState.sort" :min="1" :max="999" mode="button" :style="{width:'220px'}"/>
        </a-form-item>

        <a-form-item label="状态" field="status">
          <a-radio-group v-model="formState.status">
            <a-radio v-for="item in statusOptions" :key="item.value" :value="item.value">{{item.label}}</a-radio>
          </a-radio-group>
        </a-form-item>

        <a-form-item label="备注" field="remark">
          <a-textarea
            v-model="formState.remark"
            placeholder="简介"
            auto-size
            :maxlength="200"
            allow-clear
            show-word-limit
          />
        </a-form-item>
        <div class="form-footer">
          <a-button key="submit" html-type="submit" type="primary" :loading="pageLoading">确 定</a-button>
          <a-button class="ml-24" @click="handleCancel">取 消</a-button>
        </div>
      </a-form>
    </a-modal>
  </div>
</template>

<script lang="ts">
import { defineComponent } from "vue";

import PostAPI from "@/api/system/post";
import { statusOptions } from "@/enums/status";

export default defineComponent({
  data() {
    return {
      pageLoading: false,
      statusOptions,
      tableData: [],
      // 搜索表单
      pageData: {
        pageSize: 50,
        current: 1,
        total: 0
      },
      searchForm: {
        name: "",
        status: ""
      },
      // 部门树选择
      departOptions: [],
      fieldNames: {
        title: "name",
        key: "id",
        children: "children"
      },
      // 创建弹窗
      dialogVisible: false,
      formState: {
        id: undefined,
        name: undefined,
        code: undefined,
        remark: undefined,
        status: 1,
        sort: 1,
      },
      formRules: {
        name: [{ required: true, min: 2, message: "至少2个字符", trigger: "change" }],
        code: [{ required: true, min: 2, message: "至少2个字符", trigger: "change" }],
        status: [{ required: true, message: "状态不能为空", trigger: "blur" }],
        sort: [{ required: true, message: "排序不能为空", trigger: "blur" }],
      }
    };
  },
  mounted() {
    this.fetchTableData();
  },
  methods: {
    async fetchTableData(extraParam = {}) {
      this.pageLoading = true;
      try {
        let params = {
          page: this.pageData.current,
          limit: this.pageData.pageSize,
          ...this.searchForm
        };
        if (extraParam) {
          params = {
            ...params,
            ...extraParam
          };
        }
        const {code, data, page, total} = await PostAPI.getList(params);

        if (code === 200 && data) {
          this.tableData = data || []
          this.pageData.current = page || 1
          this.pageData.total = total || 0
        }
      } catch (err) {
        // you can report use errorHandler or other
      } finally {
        this.pageLoading = false;
      }
    },
    handleSearch(current: number) {
      this.fetchTableData({ current });
    },
    // 操作
    async handleDelete(rowData) {
      if (!rowData.id) return;

      this.pageLoading = true
      try {

        const { msg } = await PostAPI.del(rowData.id)

        this.$message.success(msg || "删除成功！");
        this.fetchTableData();
      } catch (err) {
        // you can report use errorHandler or other
      } finally {
        this.pageLoading = false;
      }
    },
    // 创建表单
    handleEdit(rowData: any) {
      this.dialogVisible = true;
      if (rowData.id) {
        this.formState = {
          id: rowData.id,
          name: rowData.name,
          code: rowData.code,
          remark: rowData.remark,
          status: rowData.status,
          sort: rowData.sort,
        };
      }
    },
    handleCancel() {
      if (this.$refs.formRef) {
        this.$refs.formRef.resetFields();
      }
      this.dialogVisible = false;
      this.formState = {
        id: undefined,
        name: undefined,
        code: undefined,
        remark: undefined,
        status: 1,
        sort: 1,
      };
    },
    async handleSubmit({ values, errors }) {
      // console.log("values:", values, "\nerrors:", errors);
      if (!errors) {
        const params = {
          ...this.formState
        }

        this.pageLoading = true
        try {

          if (params.id) {
            await PostAPI.update(params)
          } else {
            await PostAPI.create(params)
          }

          this.$message.success('保存成功！')
          await this.fetchTableData()
          this.handleCancel()
        } catch (err) {
          // you can report use errorHandler or other
        } finally {
          this.pageLoading = false;
        }
      }
    }
  }
});
</script>


<style scoped lang="less">
.form-footer {
  display: flex;
  align-items: center;
  justify-content: center;
}
</style>
